package com.zlx.filter;

import com.alibaba.fastjson.JSONObject;
import com.zlx.constants.Constant;
import com.zlx.entities.User;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @Author 周罗校
 * @Description
 * @ClassName SysFilter
 * @date 2020.09.22 18:01:11
 * 该版权归周罗校所有，最终解释权以官方为准
 */

@WebFilter("/*")
public class SysFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String uri = request.getRequestURI();
        HttpSession session = request.getSession();
        Cookie[] cookies = request.getCookies();
        if (uri.endsWith("/") || uri.endsWith("index.jsp")) {
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (Constant.LOGIN_COOKIE.equals(cookie.getName())) {
                        //解码
                        String decode = URLDecoder.decode(cookie.getValue(), "utf-8");
                        //Json字符串封装对象
                        User loginUser = JSONObject.parseObject(decode, User.class);
                        System.out.println(loginUser.getUsername());
                        session.setAttribute(Constant.LOGIN_USER, loginUser);
                        request.getRequestDispatcher("/html/commons/home.jsp").forward(request, response);
                    }
                }
            }
        } else if (uri.endsWith("home.jsp") ||
                uri.endsWith("login")||
                uri.endsWith("forget.jsp")||
                uri.endsWith("forget")||
                uri.contains("WeChat")
        ) {

        } else {
            if (session.getAttribute(Constant.LOGIN_USER) == null) {
                //具有cookie就直接放行
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (Constant.LOGIN_COOKIE.equals(cookie.getName())) {
                            chain.doFilter(request, response);
                            return;
                        }
                    }
                }else {
                    //非法登陆
                    request.setAttribute(Constant.ERROR_MSG, "非法操作，请重新登录！");
                    request.getRequestDispatcher("/index.jsp").forward(request, response);
                    return;
                }
            }
        }
        request.setAttribute(Constant.LOGIN_USER,session.getAttribute(Constant.LOGIN_USER));
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
